package algorithm1_v3;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.ObjectOutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.concurrent.Callable;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class Task1 implements Callable<Object> {

	static Logger logger = LoggerFactory.getLogger(Task1.class);

	private static void writeLeader() {
		SystemInfo info = SystemInfo.INSTANCE;
		BufferedWriter fileLeader;
		try {
			fileLeader = new BufferedWriter(new FileWriter("leader"));
			fileLeader.write(info.leader.toString());
			fileLeader.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private static void sendMessages() {
		SystemInfo info = SystemInfo.INSTANCE;

			// prozesu izenak hartu timeoutetik nere burua ezbaitako bertako
			// keyetan
			for (String host : info.timeout.keySet()) {
				try {
					Socket socket = new Socket(host, 12345);
					ObjectOutputStream clientOutputStream = new ObjectOutputStream(
							socket.getOutputStream());
					Message message = new Message(new StringBuilder(InetAddress
							.getLocalHost().getHostName()), info.recovered);
					logger.info("mezua bidalita: " + message.toString() + " "
							+ host + "-ari");
					clientOutputStream.writeObject(message);
					clientOutputStream.close();
					socket.close();
				} catch (Exception e) {
					logger.info("ERROREA: Task1 mezua bidaltzean: " + host
							+ "-ari");
				}
			}
	}

	@Override
	public Object call() throws Exception {
		// logger.info("1. Ataza Martxan");
		// Thread.sleep(info.incarnation[0]+info.timeUnit[0]); //Delay hau
		// Iniciationen sartu da scheduler exekutatzerakoan
		writeLeader();
		ScheduledExecutorService executor = Executors
				.newSingleThreadScheduledExecutor();
		executor.scheduleAtFixedRate(new Runnable() {
			public void run() {
				try {
					if (SystemInfo.INSTANCE.leader.toString().equals(
							InetAddress.getLocalHost().getHostName()))
						sendMessages();
				} catch (UnknownHostException e) {
					e.printStackTrace();
				}

			}
		}, 0, SystemInfo.INSTANCE.timeUnit[0], TimeUnit.MILLISECONDS);
		return null;
	}

}
